package org.summer.netty;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

@Slf4j
public class ByteBuffTest {

    @Test
    public void test01() {
        try (FileChannel channel = new FileInputStream("to.txt").getChannel()) {
            ByteBuffer buffer = ByteBuffer.allocate(10);
            while (true) {
                int read = channel.read(buffer);
                if (read == -1) {
                    break;
                }
                buffer.flip();
                while (buffer.hasRemaining()) {
                    System.out.println((char) buffer.get());
                }
                buffer.compact();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test02() {
        ByteBuffer buffer = ByteBuffer.allocate(16);
        buffer.put(new byte[]{1, 2, 3, 4, 5});
        buffer.flip();

        System.out.println(buffer.get());
        System.out.println(buffer.get());
        // mark position, reset method to back here
        buffer.mark();
        System.out.println(buffer.get());
        // back to mark
        log.info("call reset method");
        buffer.reset();
        System.out.println(buffer.get());
        log.info("call rewind method");
        buffer.rewind();
        System.out.println(buffer.get());

    }

    @Test
    public void test03() {
        // string convert to byteBuff
        String name = "mk";
        ByteBuffer buffer = ByteBuffer.allocate(16);
        buffer.put(name.getBytes(StandardCharsets.UTF_8));
        // Charset
        ByteBuffer buffer2 = StandardCharsets.UTF_8.encode(name);

        buffer.flip();
        System.out.println(StandardCharsets.UTF_8.decode(buffer));
        System.out.println(StandardCharsets.UTF_8.decode(buffer2));

    }

    @Test
    public void test04() {
        System.out.println(System.getProperty("user.dir"));
    }
}
